package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * projectName: gmall
 *
 * @author: 陈鹏
 * time: 2022/10/13 20:43 星期四
 * description: 订单超时监听
 */
@Component
@Log4j2
public class OrderTimeOutListener {

    @Autowired
    private OrderService orderService;

    /**
     * 监听超时的订单消息,订单若没有支付则取消订单
     * @param channel
     * @param message
     */
    @RabbitListener(queues = "order_normal_queue")
    public void orderTimeOutListener(Channel channel, Message message){
        //获取消息的属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息的编号
        long deliveryTag = messageProperties.getDeliveryTag();
        //获取需要取消的订单号
        String s = new String(message.getBody());
        try {
            System.out.println(s);
            //执行超时取消订单的操作
            orderService.cancelOrder(Long.parseLong(s));
            //确认消息
            channel.basicAck(deliveryTag, false);
        }catch (Exception e){
            try {
                if(messageProperties.getRedelivered()){
                    //拒绝过保存到日志,消息拒绝消费并丢弃
                    log.error("订单取消两次失败,订单的id为:" + s);
                    channel.basicReject(deliveryTag, false);
                }else{
                    //看消息是否被拒绝过,没有拒绝过再来一次
                    channel.basicReject(deliveryTag, true);
                }
            }catch (Exception e1){
                log.error("拒绝消息失败,订单的id为: " + s);
            }
        }
    }
}
